import React, { useCallback, useEffect, useState } from 'react';
import styled from 'styled-components';

const acrossCal = ({ id, y, col }) => {
  let cursor = id;
  const temp = [];
  const min = Math.max(id - 4, y * col);
  do {
    temp.unshift(cursor);
    cursor--;
  } while (cursor >= min);

  const max = Math.min(id + 5, (y + 1) * col);
  cursor = id + 1;
  while (cursor < max) {
    temp.push(cursor);
    cursor++;
  }
  return temp;
};

const verticalCal = ({ id, col, row }) => {
  let cursor = id;
  const temp = [];
  const min = Math.max(0, id - 4 * col);
  do {
    temp.unshift(cursor);
    cursor -= col;
  } while (cursor >= min);

  cursor = id + col;
  const max = Math.min(row * col, id + 5 * col);
  while (cursor < max) {
    temp.push(cursor);
    cursor += col;
  }
  return temp;
};
const diagonaCal = ({ id, col, row, x, y }) => {
  let cursorY = y;
  const leftward = [];
  const rightward = [];
  const minY = Math.max(0, y - 4);
  let leftId = id;
  let rightId = id;
  do {
    if (leftId >= cursorY * col && leftId < (cursorY + 1) * col) {
      leftward.unshift(leftId);
    }
    if (rightId >= cursorY * col && rightId < (cursorY + 1) * col) {
      rightward.unshift(rightId);
    }
    leftId = leftId - col - 1;
    rightId = rightId - col + 1;
    cursorY -= 1;
  } while (cursorY >= minY);

  const maxY = Math.min(row, y + 5);
  cursorY = y + 1;
  leftId = id;
  rightId = id;
  while (cursorY < maxY) {
    // debugger;
    leftId = leftId + col + 1;
    rightId = rightId + col - 1;
    if (leftId >= cursorY * col && leftId < (cursorY + 1) * col) {
      leftward.push(leftId);
    }
    if (rightId >= cursorY * col && rightId < (cursorY + 1) * col) {
      rightward.push(rightId);
    }
    cursorY++;
  }

  return [leftward, rightward];
};
const createBoard = (row, col) => {
  return new Array(row * col).fill('1').map((item, id) => {
    const x = id % col;
    const y = ~~(id / col);

    const across = acrossCal({ id, y, col });
    const vertical = verticalCal({ id, col, row });
    const [leftward, rightward] = diagonaCal({ id, col, row, x, y });
    return {
      id,
      selected: false,
      player: -1,
      matrix: {
        across,
        vertical,
        leftward,
        rightward,
      },
    };
  });
};

function FiveInARow(props) {
  const [row] = useState(20);
  const [col] = useState(20);
  const [chess] = useState(35);
  const [checkerBoard, setCheckerBoard] = useState(() => createBoard(row, col, chess));

  const [player, setPlayer] = useState(0);

  const step = useCallback(
    (id, selected) => {
      console.log(id);
      if (selected) return;

      checkerBoard[id].selected = true;
      checkerBoard[id].player = player;

      setCheckerBoard([...checkerBoard]);
      winner(id, checkerBoard);
      setPlayer(Number(!player));
    },
    [player, checkerBoard],
  );

  const winner = useCallback((id, checkerBoard) => {
    const { matrix, player } = checkerBoard[id];

    const isWinner = Object.keys(matrix).some((key) => {
      let temp = [];

      return matrix[key].some((ally) => {
        const item = checkerBoard[ally];

        if (player !== item.player || !item.selected) {
          temp = [];
          return false;
        }
        temp.push(ally);

        if (temp.length >= 5) return true;
        return false;
      });
    });

    if (isWinner) {
      console.log('>>winner');
    }
  }, []);

  return (
    <div>
      <FiveInARowContainer col={col} chess={chess}>
        {checkerBoard.map(({ id, selected, player }) => (
          <div className={`pieces player${player}` + (selected ? ' selected' : '')} key={id} onClick={() => step(id, selected)}></div>
        ))}
      </FiveInARowContainer>
    </div>
  );
}

const FiveInARowContainer = styled.div`
  margin: 0 auto;
  background: #ccc;
  width: ${({ col, chess }) => col * chess}px;
  display: flex;
  flex-wrap: wrap;
  .pieces {
    box-sizing: border-box;
    width: ${(props) => props.chess}px;
    height: ${(props) => props.chess}px;
    border: 1px solid #efefef;
    position: relative;
    &.selected {
      &:after {
        content: '';
        width: 75%;
        height: 75%;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        border-radius: 50%;
      }
    }
    &.player0 {
      &:after {
        background: #000;
      }
    }
    &.player1 {
      &:after {
        background: #fff;
      }
    }
  }
`;

export default FiveInARow;
